package system

import (
	"context"
	"encoding/json"
	"fmt"
	"jgyApi/server/global"
	"jgyApi/server/model/system"
	systemReq "jgyApi/server/model/system/request"
	"jgyApi/server/utils"
	"strconv"
	"strings"
	"time"
)

type SnService struct{}

func (s *SnService) getSn() (sn system.Sn, err error) {

	err = global.GVA_DB.First(&sn).Error
	return
}

//
//  @Description: 生成qid
//  @receiver s
//  @return qid
//  @return err
//
func (s *SnService) CreateQid (accountType int64) (qid string, err error) {
	var build strings.Builder
	if accountType == 1 {
		build.WriteString("Q")
	}else {
		build.WriteString("T")
	}
	now := time.Now()
	nowStr := strconv.Itoa(now.Year()) + fmt.Sprintf("%02d", now.Month()) + fmt.Sprintf("%02d", now.Day())
	build.WriteString(nowStr[3:])
	//第7位数字
	evenSum, oddSum := 0, 0
	for _, v := range nowStr[3:] {
		tempV := int(v - '0')
		if v%2 == 0 {
			evenSum += tempV
		} else {
			oddSum += tempV
		}
	}
	evenSum *= 3
	oddSum *= 3
	seventh := 10 - ((evenSum + oddSum) % 10)
	if seventh == 10 {
		seventh = 0
	}
	build.WriteString(strconv.Itoa(seventh))
	//第8到12位
	number := "00001"
	cacheKey := nowStr
	dr, err := utils.ParseDuration("1d")
	if err != nil {
		return "", fmt.Errorf("时间错误")
	}
	setRes := global.GVA_REDIS.SetNX(context.Background(), cacheKey, 00001, dr)
	if !setRes.Val() {
		global.GVA_REDIS.Incr(context.Background(), cacheKey)
		number = global.GVA_REDIS.Get(context.Background(), cacheKey).Val()
		length := len(number)
		if length > 5 {
			return "", fmt.Errorf("今日注册已达到上限,请明天注册吧")
		} else {
			var zeroBuild strings.Builder
			for i := 0; i < 5-length; i++ {
				zeroBuild.WriteString("0")
			}
			zeroBuild.WriteString(number)
			number = zeroBuild.String()
		}
	}
	build.WriteString(number)
	//第13位数字
	tempQid := build.String()
	evenSum, oddSum = 0, 0
	for _, v := range tempQid[2:] {
		tempV := int(v - '0')
		if v%2 == 0 {
			evenSum += tempV
		} else {
			oddSum += tempV
		}
	}
	evenSum *= 3
	oddSum *= 3
	thirteenth := 10 - ((evenSum + oddSum) % 10)
	if thirteenth == 10 {
		thirteenth = 0
	}
	build.WriteString(strconv.Itoa(thirteenth))
	qid = build.String()
	return qid, nil
}

//
// ActiveGanKaoUser
//  @Description: 激活赶考用户
//  @receiver s
//  @param active
//  @return snQidInter
//  @return err
//
func  ActiveGanKaoUser(active *systemReq.QidActive) (snQidInter *system.SnQid, err error) {
	if nil == global.GVA_DB {
		return nil, fmt.Errorf("db not init")
	}
	var snQid system.SnQid
	err = global.GVA_DB.Where("sn", active.Sn).Where("qid", active.Qid).Where("del", -1).First(&snQid).Error
	if err != nil {
		return nil, err
	}
	if snQid.IsActive == 1 {
		return nil, fmt.Errorf("该账号已经激活")
	}
	var platterID int64
	switch snQid.AccountType {
	case 1:
		var sn system.Sn
		global.GVA_DB.Where("value", active.Sn).First(&sn)
		if sn.PlatterID == 0 {
			return nil, fmt.Errorf("该账号未设置套餐")
		}
		platterID = sn.PlatterID
		break
	case 2:
		var phoneAccount system.PhoneAccount
		global.GVA_DB.Where("phone", active.Sn).First(&phoneAccount)
		if phoneAccount.PlatterID == 0 {
			return nil, fmt.Errorf("该账号未设置套餐")
		}
		platterID = phoneAccount.PlatterID
		break
	}

	var platter system.Platter
	err = global.GVA_DB.Where("id", platterID).Where("del", -1).First(&platter).Error
	if err != nil {
		return nil, err
	}
	var supplier system.LauncherSupplier
	err = global.GVA_DB.Where("name", "赶考").Where("del", -1).First(&supplier).Error
	if err != nil {
		return nil, err
	}
	type platterInfo struct {
		ID       string `json:"id"`
		TaoCanId string   `json:"taoCanId"`
		Term     string   `json:"term"`
	}
	var platterInfoArr []platterInfo
	err = json.Unmarshal([]byte(platter.Supplier), &platterInfoArr)
	if err != nil {
		return nil, err
	}
	specificationID, term := 0, 0
	for _, v := range platterInfoArr {
		id, _ := strconv.Atoi(v.ID)
		if int64(id) == supplier.ID {
			specificationID, _= strconv.Atoi(v.TaoCanId)
			term, _ = strconv.Atoi(v.Term)
		}
	}
	if specificationID == 0 || term == 0 {
		return nil, fmt.Errorf("未配置赶考套餐id或者未配置内容年限")
	}

	var a systemReq.ActiveUserReq
	a.AppID = global.GVA_CONFIG.System.GanKaoAppID
	a.SpecificationID = specificationID
	a.UID = active.Qid
	a.Timestamp = time.Now().Unix()
	//a.IsTeacher = int(snQid.IsTeacher)
	a.IsTeacher = 0  //由于现在赶考没有配置老师身份，这里默认都是学生身份激活

	service := GanKaoService{}
	_, err = service.ActiveUser(&a)
	if err != nil {
		return nil, err
	}

	snQid.IsActive = 1
	snQid.ActiveTime = a.Timestamp
	snQid.ExpireTime = a.Timestamp + int64(365*term*86400)
	global.GVA_DB.Save(snQid)
	return &snQid, nil
}
// 1.未生成qid  2.生成qid在10天体验期内  3.生成qid已过体验期 4.正式激活期间  5.正式激活过期
func (s *SnService) GetQidStatus(snQid *system.SnQid) int {
	var status int
	switch snQid.IsActive {
	case -1: //未正式激活时
		if len(snQid.Qid) == 0 {
			status = 1
		} else {
			if time.Now().Unix()-snQid.CreateTime > 10*86400 {
				status = 3
			} else {
				status = 2
			}
		}
	case 1: //正式激活
		status = 4
	}
	return status
}





